package dao

import (
	"fmt"
	"go_server/game_server/database/mysql"
	"go_server/game_server/util"
	"go_server/zinx/zlog"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type BuildCounter struct {
	Id string `gorm:"column:Id;primary"`
	RoleId int64 `gorm:"column:role_id"`
	BuildConfigId int32 `gorm:"column:build_config_id"`
	BuildServerId int32 `gorm:"column:build_server_id"`
}

//type BuildInfo struct {
//	BuildID int32
//	BuildIndex int32
//	BuildLv int32
//	BuildPosX int32
//	BuildPosZ int32
//}



func (BuildCounter) TableName() string {
	return "build_counter"
}

var(
	all_build_counter_field = util.GetGormFields(BuildCounter{})
)

func GetBuildCounterByKey(key string) *BuildCounter {
	db := mysql.GetServerDBConnection()
	var buildCounter BuildCounter
	if err := db.Select(all_build_counter_field).Where("Id=?", key).First(&buildCounter).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			zlog.Errorf("GetBuildCounterByKey ERR!!! Id: %s, err: %v", key, err)
		}
		return nil
	}
	return &buildCounter
}

func GetBuildCountersByRoleId(roleId int64) []*BuildCounter {
	db := mysql.GetServerDBConnection()
	var buildCounters []*BuildCounter
	if err := db.Select(all_build_counter_field).Where("role_id=?", roleId).Find(&buildCounters).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			zlog.Errorf("GetBuildCountersByRoleId ERR!!! role_id: %d, err: %v", roleId, err)
		}
		return nil
	}
	return buildCounters
}

func NewOrUpdateBuildCounterData(buildConfigId [][]int32, roleId int64) {
	buildCounterArr := make([]*BuildCounter, 0)
	for _, buildId := range buildConfigId {
		buildCounter := &BuildCounter{
			RoleId:       roleId,
			BuildConfigId:        buildId[0],
			BuildServerId: buildId[1],
			Id:           fmt.Sprint(roleId) + "-" + fmt.Sprint(buildId[0]),
		}
		buildCounterArr = append(buildCounterArr, buildCounter)
	}

	db := mysql.GetServerDBConnection()
	if err := db.Clauses(clause.OnConflict{
		Columns: []clause.Column{{Name: "id"}},
		DoUpdates: clause.AssignmentColumns([]string{"build_server_id"}),
	}).Create(buildCounterArr).Error; err != nil {
		zlog.Errorf("create or update BuildCounter %v data failed: %v", buildCounterArr, err)
	}
}